package com.thinksns.sociax.t4.android.verify;


import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.thinksns.sociax.android.R;
import com.thinksns.sociax.api.ApiVerify;
import com.thinksns.sociax.constant.Verify;
import com.thinksns.sociax.constant.EventBusType;
import com.thinksns.sociax.t4.android.data.StaticInApp;
import com.thinksns.sociax.t4.android.img.PhotoActivity;
import com.thinksns.sociax.t4.android.popupwindow.PopupWindowListDialog;
import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.component.SmallDialog;
import com.thinksns.sociax.t4.model.EventBusModel;
import com.thinksns.sociax.t4.model.ModelAttach;
import com.thinksns.sociax.t4.model.ModelBackMessage;
import com.thinksns.sociax.t4.model.VerifyDetails;
import com.thinksns.sociax.t4.model.VerifyModel;
import com.thinksns.sociax.t4.unit.UnitSociax;
import com.thinksns.sociax.thinksnsbase.base.BaseFragment;
import com.thinksns.sociax.thinksnsbase.utils.WordCount;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;

import static android.app.Activity.RESULT_OK;
import static com.thinksns.sociax.constant.Verify.TYPE_ORGANIZATION;

/**
 * @author LeiYan
 * @describe 认证编辑页（机构 and 非机构，type = 6 is organization verify）
 * @date 2017/7/20
 * @contact email:907238552@qq.com
 */

public class VerifyFragment extends BaseFragment {
    public static final int EXTRA_MAX_COUNT = 120; // 认证补充最大字数限制
    // 认证类型
    @BindView(R.id.ll_verify_classify)
    LinearLayout mLlVerifyClassify;
    @BindView(R.id.tv_verify_classify)
    TextView mTvVerifyClassify;
    @BindView(R.id.ll_organization_name)
    LinearLayout mLlOrganizationName;
    @BindView(R.id.et_organization_name)
    EditText mEtOrganizationName; // 机构名称

    @BindView(R.id.tv_key_name)
    TextView mTvKeyName;
    @BindView(R.id.et_manager_name)
    EditText mEtMangerName; // 负责人姓名

    @BindView(R.id.et_identify_id)
    EditText mEtIdentityId; // 身份证号码

    @BindView(R.id.et_contact)
    EditText mEtContact; // 联系方式

    @BindView(R.id.et_extra)
    EditText mEtExtra; // 认证补充

    @BindView(R.id.ll_identity_card_dec)
    LinearLayout mLlCardDec; // 选择图片描述
    @BindView(R.id.iv_camera)
    ImageView mIvCamera; // 选择图片按钮
    @BindView(R.id.ll_attach_container)
    LinearLayout mLlAttachContainer;
    @BindView(R.id.gv_attach)
    GridView mGvAttach; // 显示图片
    @BindView(R.id.btn_action)
    Button mBtnAction;
    @BindView(R.id.tv_verify_attach_dec)
    TextView mTvAttachDec;
    private boolean hasLookImage = false; //用于记录在编辑图片，用于删除更新

    private SmallDialog mSmallDialog;
    private VerifyModel mUserVerifyType; // 一级，非机构  or 机构
    private VerifyModel mSelectVerifyTypeItem; // 选中二级 认证类型项
    private VerifyDetails mVerifyDetails; // 编辑编辑时传入
    private int mVerifyType; // 机构认证=6 or 非机构认证
    private File cameraFile;// 相片文件
    private List<ModelAttach> mAttachList; // 所有（本地+网络）
    private List<String> mAttaches;// 本地图片文件
    private VerifyTypePopupWindow mClassifyPopupWindow;
    private VerifyAttachAdapter mAttachAdapter;

    /**
     * @param details  编辑页传入
     * @param userType 用户认证组（包含二级认证分类项）
     * @return
     */
    public static VerifyFragment newInstance(VerifyDetails details, VerifyModel userType) {
        VerifyFragment fragment = new VerifyFragment();
        Bundle bundle = new Bundle();
        if (userType != null)
            bundle.putSerializable("data", userType);
        if (details != null)
            bundle.putSerializable("detail", details);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onResume() {
        super.onResume();
        hasLookImage = false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_verify;
    }

    @Override
    protected void initIntentData() {
        super.initIntentData();
        if (getArguments() != null) {
            mUserVerifyType = (VerifyModel) getArguments().getSerializable("data");
            if (mUserVerifyType != null) {
                mVerifyType = Integer.parseInt(mUserVerifyType.getVerify_id());
            }
            mVerifyDetails = (VerifyDetails) getArguments().getSerializable("detail");
            if (mVerifyDetails != null && mVerifyDetails.getUsergroup_id() != mVerifyType) {
                mVerifyDetails = null;
            }
        }
    }

    @Override
    public void initView(View view) {
        if (mAttachList == null)
            mAttachList = new ArrayList<>();
        if (mAttaches == null)
            mAttaches = new ArrayList<>();
        // 根据机构or非机构隐藏机构名称输入及姓名一栏描述
        if (mVerifyType == TYPE_ORGANIZATION) {
            mTvKeyName.setText(R.string.key_manager_name);
            mEtMangerName.setHint(R.string.hint_manager_name);
            mTvAttachDec.setHint(R.string.hint_verify_attach_organization);
        } else {
            // 非机构认证隐藏机构名称输入
            mLlOrganizationName.setVisibility(View.GONE);
            mTvKeyName.setText(R.string.key_real_name);
            mEtMangerName.setHint(R.string.hint_real_name);
            mTvAttachDec.setHint(R.string.hint_verify_attach_other);
        }
        // 根据有无子分类隐藏分类一栏
        if (mUserVerifyType != null && !mUserVerifyType.getChild().isEmpty()) {
            initVerifyItemPopupWindow(mUserVerifyType.getChild());
            mLlVerifyClassify.setVisibility(View.VISIBLE);
            mSelectVerifyTypeItem = mUserVerifyType.getChild().get(0);
            mTvVerifyClassify.setText(mSelectVerifyTypeItem.getTitle());
        } else {
            mLlVerifyClassify.setVisibility(View.GONE);
        }
        // 编辑传入详情是否填写type
        if (mVerifyDetails != null) {
            if (mVerifyDetails.getUser_verified_category() != null) {
                mSelectVerifyTypeItem = mVerifyDetails.getUser_verified_category();
            }
            mAttachList.addAll(mVerifyDetails.getAttach_id());
        }
        if (mSmallDialog == null)
            mSmallDialog = new SmallDialog(getActivity(), getString(R.string.progress_committing));
        mAttachAdapter = new VerifyAttachAdapter(getActivity(), mGvAttach);
        mGvAttach.setAdapter(mAttachAdapter);
        mAttachAdapter.setData(mAttachList);
        showAttachView(!mAttachList.isEmpty());
    }

    @Override
    protected void initData() {
        super.initData();
        showUserVerifyInfo(mVerifyDetails);
    }

    @Override
    protected void initListener() {
        super.initListener();
        WordCount wordCount = new WordCount(mEtExtra, EXTRA_MAX_COUNT, false);
        wordCount.setTextChangeListener(new WordCount.TextChangeListener() {
            @Override
            public void textOverCount(int maxCount) {
                ToastUtils.showToast(String.format(getString(R.string.format_out_of_content_length), maxCount));
            }

            @Override
            public void textChange(Editable editable) {

            }
        });
        mEtExtra.addTextChangedListener(wordCount);
        mIvCamera.setOnClickListener(this);
        mBtnAction.setOnClickListener(this);
        mTvVerifyClassify.setOnClickListener(this);
        mTvAttachDec.setOnClickListener(this);
        mGvAttach.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == mAttachList.size()) {
                    showSelectImageDialog();
                } else {
                    hasLookImage = true;
                    Intent intent = new Intent(getActivity(), PhotoActivity.class);
                    intent.putExtra("ID", position);
                    List<String> data = new ArrayList<String>();
                    for (ModelAttach attach : mAttachList) {
                        data.add(attach.getImage_url());
                    }
                    intent.putStringArrayListExtra("data", (ArrayList<String>) data);
                    //预览选择的照片
                    startActivityForResult(intent, StaticInApp.UPLOAD_WEIBO);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_camera:
            case R.id.tv_verify_attach_dec:
                showSelectImageDialog();
                break;
            case R.id.btn_action:
                if (checkData()) {
                    doCommit(packageData());
                }
                break;
            case R.id.tv_verify_classify:
                if (mClassifyPopupWindow != null) {
                    mClassifyPopupWindow.show(mBtnAction, Gravity.BOTTOM);
                }
                break;
        }
    }

    private boolean checkData() {
        if (mLlVerifyClassify.getVisibility() == View.VISIBLE && TextUtils.isEmpty(mTvVerifyClassify.getText())) {
            ToastUtils.showToast(getString(R.string.tip_pre_pls_input));
            return false;
        }
        if (mVerifyType == TYPE_ORGANIZATION && TextUtils.isEmpty(mEtOrganizationName.getText())) {
            ToastUtils.showToast(getString(R.string.hint_organization_name));
            return false;
        }
        if (TextUtils.isEmpty(mEtMangerName.getText())) {
            if (mVerifyType == Verify.TYPE_ORGANIZATION) {
                ToastUtils.showToast(getString(R.string.tip_pre_pls_input) + getString(R.string.hint_manager_name));
            } else {
                ToastUtils.showToast(getString(R.string.tip_pre_pls_input) + getString(R.string.hint_real_name));
            }
            return false;
        }
        if (TextUtils.isEmpty(mEtIdentityId.getText())) {
            ToastUtils.showToast(getString(R.string.tip_pre_pls_input) + getString(R.string.hint_identity_id));
            return false;
        }
        if (TextUtils.isEmpty(mEtContact.getText())) {
            ToastUtils.showToast(getString(R.string.tip_pre_pls_input) + getString(R.string.hint_contact_way));
            return false;
        }
        return true;
    }

    private VerifyDetails packageData() {
        VerifyDetails details = new VerifyDetails();
        details.setUsergroup_id(mVerifyType);
        details.setUser_verified_category(mSelectVerifyTypeItem); // 认证分类选项
        details.setCompany(mEtOrganizationName.getText().toString().trim()); // 机构名称
        details.setRealname(mEtMangerName.getText().toString().trim());
        details.setIdcard(mEtIdentityId.getText().toString().trim());
        details.setPhone(mEtContact.getText().toString().trim());
        details.setReason(String.valueOf(mEtExtra.getText()).trim());
        return details;
    }

    /**
     * 点击提交按钮，判断是否有附件
     *
     * @param verifyDetail
     */
    private void doCommit(VerifyDetails verifyDetail) {
        mSmallDialog.show();
        String attachId = "";
        for (ModelAttach attach : mAttachList) {
            if (!TextUtils.isEmpty(attach.getAttach_id())) {
                attachId += attach.getAttach_id() + "|";
            }
        }
        if (mAttaches != null && !mAttaches.isEmpty()) {
            uploadPic(attachId, mAttaches, verifyDetail);
        } else {
            commitVerifyInfo(verifyDetail, TextUtils.isEmpty(attachId) ? attachId : attachId.substring(0, attachId.length()));
        }
    }

    /**
     * 上传图片
     *
     * @param oldAttachIds
     * @param path
     */
    private void uploadPic(final String oldAttachIds, List<String> path, final VerifyDetails detail) {
        ApiVerify.getInstance().uploadPic(path, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showToast(R.string.net_fail);
                mSmallDialog.dismiss();
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject obj = new JSONObject(response);
                    if (1 == obj.optInt("status")) {
                        commitVerifyInfo(detail, (TextUtils.isEmpty(oldAttachIds) ? "" : oldAttachIds) + obj.optString("attach_ids"));
                    } else {
                        mSmallDialog.dismiss();
                        ToastUtils.showToast(obj.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 提交认证信息
     *
     * @param attachId
     */
    private void commitVerifyInfo(VerifyDetails detail, String attachId) {
        ApiVerify.getInstance().doAuthenticate(detail, attachId, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mSmallDialog.dismiss();
                ToastUtils.showToast(R.string.net_fail);
            }

            @Override
            public void onResponse(String response, int id) {
                ModelBackMessage backMsg = new ModelBackMessage(response);
                mSmallDialog.dismiss();
                ToastUtils.showToast(backMsg.getMsg());
                if (backMsg.isSuccess()) {
                    getActivity().finish();
                }
            }
        });
    }

    private void showSelectImageDialog() {
        final PopupWindowListDialog.Builder builder = new PopupWindowListDialog.Builder(getContext());
        builder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    selectMultiMedia(Verify.MAX_ATTACH_COUNT);
                } else if (position == 1) {
                    //拍摄图片
                    selectPicFromCamera();
                } else {
                    builder.dimss();
                }
            }
        });

        List<String> datas = Arrays.asList(getResources().getStringArray(R.array.item_select_photo));
        builder.create(datas);

    }

    private void selectPicFromCamera() {
        if (!UnitSociax.isExitsSdcard()) {
            ToastUtils.showToast(R.string.tip_sd_card_unmounted);
            return;
        }
        cameraFile = new File(Environment.getExternalStorageDirectory(),
                StaticInApp.cache);
        if (!cameraFile.exists())
            cameraFile.mkdirs();
        cameraFile = new File(cameraFile, System.currentTimeMillis() + ".jpg");
        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
                MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                StaticInApp.CAMERA_IMAGE);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case StaticInApp.CAMERA_IMAGE:
                    if (cameraFile != null && cameraFile.exists()) {
                        String cameraPath = cameraFile.getAbsolutePath();
                        ModelAttach attach = new ModelAttach();
                        attach.setImage_url(cameraPath);
                        mAttachList.add(attach);
                        mAttaches.add(cameraPath);
                        showAttachView(!mAttachList.isEmpty());
                        mAttachAdapter.notifyDataSetChanged();
                    }
                    break;
                case StaticInApp.LOCAL_IMAGE:
                    if (data != null) {
                        List<String> photoList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                        ModelAttach addAttach;
                        for (String addr : photoList) {
                            if (mAttachList.size() == Verify.MAX_ATTACH_COUNT)
                                break;
                            if (!mAttaches.contains(addr)) {
                                mAttaches.add(addr);
                                addAttach = new ModelAttach();
                                addAttach.setImage_url(addr);
                                mAttachList.add(addAttach);
                            }
                        }
                        showAttachView(!mAttachList.isEmpty());
                        mAttachAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    /**
     * init popupWindow for select verify type
     *
     * @param typeItemList
     */
    private void initVerifyItemPopupWindow(List<VerifyModel> typeItemList) {
        mClassifyPopupWindow = new VerifyTypePopupWindow(getActivity(), typeItemList);
        mClassifyPopupWindow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelectVerifyTypeItem = (VerifyModel) v.getTag();
                mTvVerifyClassify.setText(mSelectVerifyTypeItem.getTitle());
            }
        });
    }

    /**
     * 显示图片还是文字
     *
     * @param path null hide imageView,else show path
     */
    private void showCardImageView(Object path) {
        if (path == null || TextUtils.isEmpty(String.valueOf(path))) {
            mLlCardDec.setVisibility(View.VISIBLE);
            return;
        }
        mLlCardDec.setVisibility(View.GONE);
        if (path instanceof String) {
//            UnitSociax.loadImageNoAnim(getActivity(), mIvCard, String.valueOf(path), R.drawable.image120x120);
        } else if (path instanceof Bitmap) {
        }
    }

    private void showUserVerifyInfo(VerifyDetails details) {
        if (details == null) return;
        if (mSelectVerifyTypeItem != null) {
            mTvVerifyClassify.setText(mSelectVerifyTypeItem.getTitle());
        }
        // 机构名称
        if (!TextUtils.isEmpty(details.getCompany())) {
            mEtOrganizationName.setText(details.getCompany());
        }
        // 真实姓名 or 负责人姓名
        if (!TextUtils.isEmpty(details.getRealname())) {
            mEtMangerName.setText(details.getRealname());
        }
        // 身份证号
        if (!TextUtils.isEmpty(details.getIdcard())) {
            mEtIdentityId.setText(details.getIdcard());
        }
        // 联系方式
        if (!TextUtils.isEmpty(details.getPhone())) {
            mEtContact.setText(details.getPhone());
        }
        // 认证补充
        if (!TextUtils.isEmpty(details.getReason())) {
            mEtExtra.setText(details.getReason());
        }
        // 附件（身份证正面图片）
        if (details.getAttach_id() != null && !details.getAttach_id().isEmpty()) {
//            mAttachList = details.getAttach_id().get(0).getImage_url();
            showCardImageView(mAttachList);
        }
    }

    public void refreshUserVerifyType(VerifyModel model, VerifyDetails details) {
        this.mUserVerifyType = model;
        this.mVerifyType = Integer.parseInt(model.getVerify_id());
        this.mVerifyDetails = details;
        if (details != null && details.getUsergroup_id() != mVerifyType) {
            mVerifyDetails = null;
        }
        /*避免切换其他分类时图片重复加载 8.7.2017*/
        if (mAttachList != null){
            mAttachList.clear();
        }
        if (mAttaches != null){
            mAttaches.clear();
        }
        initView(null);
        showUserVerifyInfo(mVerifyDetails);
    }


    private void showAttachView(boolean isShow) {
        if (isShow) {
            mLlCardDec.setVisibility(View.GONE);
            mLlAttachContainer.setVisibility(View.VISIBLE);
        } else {
            mLlCardDec.setVisibility(View.VISIBLE);
            mLlAttachContainer.setVisibility(View.GONE);
        }
    }

    /**
     * 选择相册
     *
     * @param maxCount
     */
    private void selectMultiMedia(int maxCount) {
        Intent getImage = new Intent(getActivity(), MultiImageSelectorActivity.class);
        getImage.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxCount);
        getImage.putExtra(MultiImageSelectorActivity.SHOW_CATEGORY, MultiImageSelectorActivity.SHOW_IMG_ONLY);
        getImage.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
        getImage.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        getImage.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, (ArrayList<String>) mAttaches);
        startActivityForResult(getImage, StaticInApp.LOCAL_IMAGE);
    }

    @Override
    protected boolean needEventBus() {
        return true;
    }

    @Subscribe
    public void receiveDeleteImage(EventBusModel msg) {
        if (hasLookImage && msg.getType() == EventBusType.DELETE_IMAGE) {
            String deleteUrlOrPath = msg.getData();
            mAttaches.remove(deleteUrlOrPath);
            for (int i = 0; i < mAttachList.size(); i++) {
                if (deleteUrlOrPath.equals(mAttachList.get(i).getImage_url())) {
                    mAttachList.remove(i);
                    break;
                }
            }
            mAttachAdapter.notifyDataSetChanged();
        }
    }
}
